package com.gxc.mq.consumer;

import com.gxc.entity.User;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author GongXincheng
 * @since 2019-09-03 10:33
 */
@Component
public class TestQueueConsumer {

    /**
     * 接收普通字符串.
     */
    //@RabbitListener(queues = "${gxc.queue.name.test-queue}")
    public void testQueueConsumer(Message message, Channel channel) throws IOException {
        try {
            System.out.println("TestQueueConsumer：" + new String(message.getBody(), StandardCharsets.UTF_8));
            System.out.println("Header -> key -> value = " + message.getMessageProperties().getHeaders().get("key"));
            int i = 1 / 0;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            // 手动应答
            //channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }

    }

    /**
     * 接收对象. 将数组转成对象.
     */
    //@RabbitListener(queues = "${gxc.queue.name.test-queue}")
    public void testQueueConsumer2(Message message, Channel channel) {
        try {
            // 将字节数组转为对象.
            byte[] body = message.getBody();
            ByteArrayInputStream bi = new ByteArrayInputStream(body);
            ObjectInputStream oi = new ObjectInputStream(bi);

            User user = (User) oi.readObject();
            System.out.println(user);
        } catch (Exception e) {
            System.out.println("Error：" + e.getMessage());
        }
    }

    /**
     * 接收对象，直接接收对象.
     */
    @RabbitListener(queues = "${gxc.queue.name.test-queue}")
    public void testQueueConsumer3(User user) {
        System.out.println(user);
    }
}
